import {createRouter,createWebHistory} from 'vue-router'
import store from "../store";
import admView from './adm'
import sysViews from "./sys";
import singleForm from './singlepageForm'
import homeDefault from './home-default'

import {initUserMenus} from "../network/sys/menu";
import {getUserInfo} from "../network/login/login";

const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        component: ()=>import('../views/Login.vue')
    },
    {

        path: '/home',
        name: 'home',
        component: ()=>import('../views/Home.vue'),
        meta: {
            name: 'home',
            requireAuth: true
        },
        redirect: '/home/personal-platform',
        children:[].concat(homeDefault).concat(admView).concat(sysViews)
    },
].concat(singleForm)

const router = createRouter({
    history:createWebHistory(),
    routes
})

//前端路由前置守卫
router.beforeEach((to,from,next)=>{
    // console.log('进入导航守卫beforeEach...');
    sessionStorage.removeItem('Network Error');
    //判断用户是否拥有令牌
    if(localStorage.getItem('tokenStr') && to.path !== '/login') {
        initMenu(next,to);//初始化用户权限菜单
        initLoginUser();//前端缓存登录用户信息
    }else if (to.meta.requireAuth && !store.state.loginUser.empName){
        router.replace('/login');
    }
    next();
})
//缓存登录用户信息
function initLoginUser(){
    if(store.state.loginUser.empName === null){//登录用户姓名为空，初始化用户信息
        // console.log('获取登录用户信息...')
        getUserInfo().then(vo=>{//获取登录用户的信息
            store.commit('setLoginUser',vo.data);
            console.log('登录员工信息',vo);
        })
    }
}
//初始化并缓存用户权限菜单
function initMenu(next,to){
    // console.log('router',router.options.routes)
    if(store.state.routes.length > 0){
        // console.log('用户菜单已存在')
        return;
    }
    // console.log('获取用户权限菜单..')
    initUserMenus().then(vo=>{
        if(vo){
            // console.log('菜单vo',vo.data)
            let fmtRoutes = formatRoutes(vo.data);
            // console.log('fmtRoutes',fmtRoutes);
            initUserComponent(fmtRoutes);
            //保存到store中
            store.commit('initRoutes',fmtRoutes);
            next({...to,replace:true});
            //使用next({ ...to, replace: true })来确保addRoutes()时动态添加的路由已经被完全加载上去
            //next({ ...to})如果参数to不能找到对应的路由的话，就再执行一次beforeEach((to, from, next)直到其中的next({ ...to})能找到对应的路由为止。
            //next({ ...to, replace: true })中的replace: true只是一个设置信息，告诉VUE本次操作后，不能通过浏览器后退按钮，返回前一个路由。
            if(to.matched.length===0){//to.matched保留了与目标地址匹配的路由地址
                router.push(to.path);
            }
        }else{
            console.log('没有获取到信息。。。。')
        }
    })
    
}
const modules = import.meta.glob('../views/**/*.vue')
//将查询的列表写成路由格式
export const formatRoutes = (routes) =>{
    let fmtRoutes = [];//接收结果集的变量
    routes.forEach(router=>{
        if(router.type!==2){//按钮菜单不需要加载
            let{
                path,
                component,
                menuName,
                iconCls,
                iconUrl,
                children,
                type
            } = router;
            //查找子路由
            if(children && children instanceof Array){
                children = formatRoutes(children);
            }
            
            // let routerComponent = null;
            // if(router.type===0){//目录菜单组件
            //     // console.log('加载目录',router.menuName);
            //     routerComponent = modules[`${'../views/com/Layout.vue'}`];
            // }else{
            //     routerComponent = modules[`${'../views' + component + '.vue'}`];
            // }
            let fmRouter = {
                path: path,
                name: menuName,
                iconCls: iconCls,
                iconUrl: iconUrl,
                children: children,
                component: router.type===0?modules[`${'../views/com/Layout.vue'}`]:modules[`${'../views' + component + '.vue'}`],
                // component: routerComponent,
                // component: modules[`${'../views' + component + '.vue'}`],
                type: type
            }
            fmtRoutes.push(fmRouter);
        }
    })
    return fmtRoutes;
}
//初始化用户首页菜单组件
export const initUserComponent = (routes)=>{
    routes.forEach(route=>{
        if(route.type === 1){//菜单页面
            router.addRoute('home',route);
        }
        if(route.children && route.children instanceof Array){
            // initUserComponent(route.children,router)
            initUserComponent(route.children)
        }
    })
}

export default router
